var status = 0; // 0: 编辑 1： 增加

var thisPage = {
    _rows: 0,
    first: 0,
    // 初始化页面
    OnPageLoad: function () {
        thisPage.FetchAll();
    },
    // 得到数据列表信息
    FetchAll: function () {
        $.ajax({
            type: "POST",
            url: parent.basePath + "/admin/privilege/fetchAllResource.html",
            timeout: 60 * 1000,
            data: {},
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function (data) {
            }
        }).done(function (data) {
            thisPage.BuildDataTable(data);
        }).fail(function (data) {
            ajaxError(data, 1);
        }).always(function () {
            if (thisPage.first === 0) {
                thisPage.first = 1;
            }
        });
    },
    // 构建数据列表
    BuildDataTable: function (result) {
        // 得到数据列表
        $("#tabData01 tbody").empty();
        if (result === null) {
            thisPage._rows = 0;
            $('#loading').hide();
            return false;
        }
        var content = '';
        if (result.length > 0) {
            for (var i = 0; i < result.length; i++) {
                var id = result[i].resourceId;
                if ((result[i].level) === 0) {
                    content += '<tr data-tt-id="' + id + '">';
                } else {
                    content += '<tr data-tt-id="' + id + '" data-tt-parent-id="' + result[i].parentId + '">';
                }
                content += '<td style="text-align:center;">' + (i + 1) + '</td>';
                var lpad = 5 + 24 * result[i].level + 'px';
                content += '<td style="padding-left:' + lpad + '"><input style="vertical-align:-2px;" type="checkbox" id="r-' + result[i].resourceId + '" _parentId="' + result[i].parentId + '" name="ResourcePrivilege" _msh_id="' + result[i].resourceId + '" value ="' + result[i].resourceName + '" onchange="checkField($(this))"><label class="normal" style="margin:0 8px 0 3px;" for="r-' + result[i].resourceId + '">' + result[i].resourceName + '</label></td>';
                //content += '<td style="padding-left:' + lpad + '"><label class="btn" style="width:23px; vertical-align:middle; padding-top:1px;" for="r-' + result[i].resourceId + '"><input id="r-' + result[i].resourceId + '" name="ResourcePrivilege" type="checkbox" _msh_id="' + result[i].resourceId + '" value ="' + result[i].resourceName + '" onclick="checkField($(this));" value="' + id + '"/><i></i><span></span></label><label class="normal" style="vertical-align:middle;" for="r-' + result[i].resourceId + '">' + result[i].resourceName + '</label></td>';
                var actList = result[i].actionList;
                if (actList.length === 0) {
                    content += '<td>' + "" + '</td>';
                } else {
                    content += '<td>';
                    for (var j = 0; j < actList.length; j++) {
                        var aid = "a-" + result[i].resourceId + "-" + actList[j].actionId;
                        var mr = 0;
                        if ((j > 0) && (j === (actList.length - 1))) {
                        } else {
                            mr = 20;
                        }
                        content += '<input style="vertical-align:-2px;" type="checkbox" id="' + aid + '" name="ActionPrivilege" _msh_rid="' + result[i].resourceId + '" _msh_aid="' + actList[j].actionId + '" value ="xxx" onchange="checkField($(this))"><label class="normal" style="margin:0 8px 0 3px;" for="' + aid + '">' + actList[j].actionName + '</label>';
                    }
                    content += '</td>';
                }
                content += '</tr>';
                $("#tabData01 tbody").append(content);
                content = '';
            }
        }
        thisPage._rows = result.length;
        //setOneTableRowColor("tabData01");

        $("input[name='ResourcePrivilege']").bind("click", thisPage.SetResourceCheckMarkFlag);
        thisPage.InitCheckMarkFlag();
        // 自适应高度设置
        SetSlaveTableHeight();
        $('#loading').hide();
    },
    // 得到系统资源权限
    GetResourcePrivilege: function () {
        var resourcePrivilegeList = [];
        $("input[type='checkbox'][name='ResourcePrivilege']:checked").each(function () {
            var item = {};
            item['userName'] = $("#UserName").val();
            item['resourceId'] = parseInt($(this).attr("_msh_id"));
            item['actionId'] = 0;
            item['accessFlag'] = "1";
            resourcePrivilegeList.push(item);
        });
        return resourcePrivilegeList;
    },
    // 取得操作权限
    GetActionPrivilege: function () {
        var actionPrivilegeList = [];
        $("input[type='checkbox'][name='ActionPrivilege']:checked").each(function () {
            var item = {};
            item['userName'] = $("#UserName").val();
            item['resourceId'] = parseInt($(this).attr("_msh_rid"));
            item['actionId'] = parseInt($(this).attr("_msh_aid"));
            item['accessFlag'] = "1";
            actionPrivilegeList.push(item);
        });
        return actionPrivilegeList;
    },
    // 授权
    GrantPermission: function () {
        if ($("#MemberName").val() === "") {
            ShowErrorMessagePanel('请选择一个要授权的成员用户。');
            return;
        }
        var item = {};
        item['UserName'] = $("#UserName").val();
        item['ResourceAccessList'] = thisPage.GetResourcePrivilege();
        item['ActionAccessList'] = thisPage.GetActionPrivilege();
        $.ajax({
            type: "POST",
            url: parent.basePath + "/admin/privilege/grantPrivilege.html",
            timeout: 60 * 1000,
            data: JSON.stringify(item),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function (data) {
            }
        }).done(function (data) {
            if (data === true) {
                ShowSuccessMessagePanel('授权成功!');
            }
        }).fail(function (data) {
            ajaxError(data, 1);
        }).always(function () {
        });
    },
    // 下面设置一些checkbox相互之间的吻合关系
    SetResourceCheckMarkFlag: function () {
        var id = $(this).attr("_msh_id");
        if (!$(this).is(':checked')) {
            // 设置其所属子节点状态
            iterationX1($(this).attr("_msh_id"));
            // 检查有没有被选择的同类子节点
            var p_checked = false;
            $("input[_parentId='" + $(this).attr("_parentId") + "']").each(function () {
                if ($(this).is(':checked')) {
                    p_checked = true;
                }
            });
            // 设置父节点状态
            $("input[_msh_id='" + $(this).attr("_parentId") + "']").prop("checked", p_checked);
            checkField($("input[_msh_id='" + $(this).attr("_parentId") + "']"));
            thisPage.SetActionCheckMarkFlag($("input[_msh_id='" + $(this).attr("_parentId") + "']"), $(this).attr("_parentId"));
            if ((!p_checked) && ($(this).attr("_parentId") > 0)) {
                $("input[_parentId='" + $(this).attr("_parentId") + "']").each(function () {
                    $(this).prop("disabled", true);
                    thisPage.SetActionCheckMarkFlag($(this), $(this).attr("_msh_id"));
                    checkField($(this));
                });
            }
        } else {
            $("input[_parentId='" + id + "']").each(function () {
                $(this).prop("disabled", false);
                checkField($(this));
            });
            $("input[_msh_id='" + $(this).attr("_parentId") + "']").prop("checked", true);
            checkField($("input[_msh_id='" + $(this).attr("_parentId") + "']"));
            thisPage.SetActionCheckMarkFlag($("input[_msh_id='" + $(this).attr("_parentId") + "']"), $("input[_msh_id='" + $(this).attr("_parentId") + "']").attr("_msh_id"));
            iterationX2(id);
        }
        thisPage.SetActionCheckMarkFlag($(this), id);
        checkField($(this));
    },
    SetActionCheckMarkFlag: function ($self, id) {
        if (!$self.is(':checked')) {
            $("input[_msh_rid='" + id + "']").each(function () {
                $(this).prop("checked", false);
                $(this).prop("disabled", true);
                checkField($(this));
            });
        } else {
            $("input[_msh_rid='" + id + "']").each(function () {
                $(this).prop("disabled", false);
                checkField($(this));
            });
        }
    },
    SetAllCheckMarkFlag: function () {
        $("input[name='ResourcePrivilege']").each(function () {
            $(this).prop("disabled", false);
            $(this).prop("checked", true);
            checkField($(this));
        });
        $("input[name='ActionPrivilege']").each(function () {
            $(this).prop("disabled", false);
            $(this).prop("checked", true);
            checkField($(this));
        });
    },
    InitCheckMarkFlag: function () {
        $("input[name='ResourcePrivilege']").each(function () {
            $(this).prop("checked", false);
            checkField($(this));
            thisPage.SetActionCheckMarkFlag($(this), $(this).attr("_msh_id"));
        });
    },
    // 选择成员用户
    DoChoiceMemberName: function () {
        showModal(1295, 538, '选择系统用户', parent.basePath + '/admin/membership/choice.html?flag=0', null,
                function ($dialog) {
                    var _exist = $.inArray($dialog, parent.arrDialog);
                    if (_exist >= 0) {
                        parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
                    }
                    // 设置该用户的权限状态
                    if (parent.choice_success) {
                        $("#UserName").val(parent.arrChoice[0][0]);
                        $("#MemberName").val(parent.arrChoice[0][1]);
                        //清空数组
                        parent.arrChoice.splice(0, parent.arrChoice.length);
                        parent.choice_success = false;
                        var item = {};
                        item['UserName'] = $("#UserName").val();
                        $.ajax({
                            type: "POST",
                            url: parent.basePath + "/admin/privilege/fetchPrevilegeByUserName.html",
                            timeout: 60 * 1000,
                            data: JSON.stringify(item),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            beforeSend: function (data) {
                            }
                        }).done(function (data) {
                            var rpList = data.ResourceAccessList;
                            var apList = data.ActionAccessList;
                            // 首先设置全部资源权限为否
                            $("input[name='ResourcePrivilege']").each(function () {
                                if ($(this).prop("data-tt-parent-id") === undefined) {
                                    $(this).prop("checked", false);
                                } else {
                                    $(this).prop("disabled", true);
                                    $(this).prop("checked", false);
                                }

                                checkField($(this));
                                thisPage.SetActionCheckMarkFlag($(this), $(this).attr("_msh_id"));
                            });
                            // 根据权限标记显示该成员用户的权相状态
                            if (rpList !== null && rpList.length > 0) {
                                for (var i = 0; i < rpList.length; i++) {
                                    var $obj = $("#r-" + rpList[i].resourceId);
                                    $obj.attr("_msh_id", rpList[i].resourceId);
                                    if (parseInt(rpList[i].accessFlag) === 1) {
                                        $obj.prop("checked", true);
                                        $obj.prop("disabled", false);
                                    } else {
                                        $obj.prop("checked", false);
                                    }
                                    checkField($obj);
                                    thisPage.SetActionCheckMarkFlag($obj, $obj.attr("_msh_id"));
                                }
                            }

                            if (apList !== null && apList.length > 0) {
                                for (var i = 0; i < apList.length; i++) {
                                    var $obj = $("#a-" + apList[i].resourceId + "-" + apList[i].actionId);
                                    if (parseInt(apList[i].accessFlag) === 1) {
                                        $obj.prop("checked", true);
                                        $obj.prop("disabled", false);
                                    } else {
                                        $obj.prop("checked", false);
                                    }
                                    checkField($obj);
                                }
                            } else {
                                $("input[name='ActionPrivilege']").each(function () {
                                    $(this).prop("disabled", true);
                                    $(this).prop("checked", false);
                                });
                                checkField($(this));
                            }
                        }).fail(function (data) {
                            ajaxError(data, 1);
                        }).always(function () {
                        });
                    }
                });
    },
    // 复制权限
    CopyPrivilege: function () {
        if (parseInt($("#UserName").val()) === 0) {
            ShowErrorMessagePanel('请选择一个系统用户。');
            return false;
        }
        showModal(1295, 538, '选择系统用户', parent.basePath + '/admin/membership/choice.html?flag=1', null,
                function ($dialog) {
                    var _exist = $.inArray($dialog, parent.arrDialog);
                    if (_exist >= 0) {
                        parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
                    }
                    //做列表选择设置
                    if (choice_success) {
                        var itemResult = new Array();
                        for (var i = 0; i < parent.arrChoice[0].length; i++) {
                            itemResult.push(parent.arrChoice[0][i]['UserName']);
                        }
                        // 清空数组
                        parent.arrChoice.splice(0, parent.arrChoice.length);
                        choice_success = false;
                        var item = {};
                        item['UserName'] = $("#UserName").val();
                        item['OtherMemberList'] = itemResult;
                        $.ajax({
                            type: "POST",
                            url: parent.basePath + "/admin/privilege/copyPrivilege.html",
                            timeout: 60 * 1000,
                            data: JSON.stringify(item),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            beforeSend: function () {
                            }
                        }).done(function (data) {
                            if (data > 0) {
                                ShowSuccessMessagePanel('权限复制成功。');
                            }
                        }).fail(function (data) {
                            ajaxError(data, 1);
                        }).always(function () {
                        });
                    } else {
                        // 清空数组
                        parent.arrChoice.splice(0, parent.arrChoice.length);
                    }
                });
    },
    Revoke: function () {
        if (parseInt($("#UserName").val()) === 0) {
            ShowErrorMessagePanel('请选择一个系统用户。');
            return false;
        }
        let item = {};
        item['UserName'] = $("#UserName").val();
        $.ajax({
            type: "POST",
            url: parent.basePath + "/admin/privilege/revoke.html",
            timeout: 60 * 1000,
            data: JSON.stringify(item),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
            }
        }).done(function (data) {
            if (data > 0) {
                $("input[type='checkbox']").prop("checked", false);
                $("input[name='ResourcePrivilege']").each(function () {
                    //$(this).prop("disabled", true);
                    $(this).prop("checked", false);
                    checkField($(this));
                });
                $("input[name='ActionPrivilege']").each(function () {
                    $(this).prop("disabled", true);
                    $(this).prop("checked", false);
                    checkField($(this));
                });

                ShowSuccessMessagePanel('权限回收成功。');
            }
        }).fail(function (data) {
            ajaxError(data, 1);
        }).always(function () {
        });
    }
};
//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    thisPage.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
    SetSlaveTableHeight();
}

// 根据窗口大小设置明细列表的高度（自适应高度）
function SetSlaveTableHeight() {
    var h = $(window).height();
    var _rc = Math.floor((h - 147) / 25);
    var _dh = _rc * 25;
    var _tah = thisPage._rows * 25;
    _dh = (_tah >= _dh) ? _dh : _tah;
    $("#divD1").css({"max-height": _dh, height: _dh});
}

//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
function checkField($self) {
    if ($self.is(':disabled')) {
        $self.next().removeClass('disabled').addClass('disabled');
    }
    if (!$self.is(':disabled')) {
        $self.next().removeClass('disabled');
    }

    if ($self.is(':checked')) {
        $self.next().removeClass('selected').addClass('selected');
    }
    if (!$self.is(':checked')) {
        $self.next().removeClass('selected');
    }
}

function iterationX1(id) {
    $("input[_parentId='" + id + "']").each(function () {
        $(this).prop("checked", false);
        $(this).prop("disabled", true);
        thisPage.SetActionCheckMarkFlag($(this), $(this).attr("_msh_id"));
        checkField($(this));
        if (!$(this).is(':checked')) {
            iterationX1($(this).attr("_msh_id"));
        }
    });
}
function iterationX2(id) {
    $("input[_parentId='" + id + "']").each(function () {
        $(this).prop("disabled", false);
        checkField($(this));
    });
    $("input[_msh_id='" + $(this).attr("_parentId") + "']").prop("checked", true);
    $("input[_parentId='" + id + "']").each(function () {
        $(this).prop("checked", true);
        thisPage.SetActionCheckMarkFlag($(this), $(this).attr("_msh_id"));
        checkField($(this));
        if ($(this).is(':checked')) {
            iterationX2($(this).attr("_msh_id"));
        }
    });
    // 对该资源的操作进行设置
    $("input[_msh_rid='" + id + "']").each(function () {
        $(this).prop("checked", true);
        thisPage.SetActionCheckMarkFlag($(this), $(this).attr("_msh_id"));
        checkField($(this));
        if ($(this).is(':checked')) {
            iterationX2($(this).attr("_msh_id"));
        }
    });
}